package fct.mpc.snipehunter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import fct.mpc.utils.HuntingGrounds;

public class SnipeHunterMenuActivity extends ListActivity
{
	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		new LoadAssetsTask().execute();
	}

	private class LoadAssetsTask extends AsyncTask<Void, Integer, Void>  
	{
		@Override
		protected void onPreExecute()
		{
			progressDialog = ProgressDialog.show(SnipeHunterMenuActivity.this,"Loading...", "Loading application, please wait...", false, false);
		}

		@Override
		protected Void doInBackground(Void... params)
		{
			synchronized (this)  
			{
				AssetManager assetManager = getAssets();

				// Build the hunting grounds
				try
				{
					InputStream inputStream = assetManager.open("hunting_grounds.xml");

					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
					try
					{


						DocumentBuilder builder = factory.newDocumentBuilder();
						Document dom = builder.parse(inputStream);

						Element root = dom.getDocumentElement();
						NodeList items = root.getElementsByTagName("hunting_ground");

						for (int i=0; i<items.getLength(); i++)
						{
							String huntingGroundName = "";
							double huntingGroundNorth = 0;
							double huntingGroundSouth = 0;
							double huntingGroundEast = 0;
							double huntingGroundWest = 0;

							Node item = items.item(i);
							NodeList properties = item.getChildNodes();

							for (int j=0; j<properties.getLength(); j++)
							{
								Node property = properties.item(j);
								String name = property.getNodeName();

								if (name.equalsIgnoreCase("name"))
									huntingGroundName = property.getFirstChild().getNodeValue();
								else if (name.equalsIgnoreCase("north"))
									huntingGroundNorth = Double.parseDouble(property.getFirstChild().getNodeValue());
								else if (name.equalsIgnoreCase("south"))			                       
									huntingGroundSouth = Double.parseDouble(property.getFirstChild().getNodeValue());
								else if (name.equalsIgnoreCase("east"))
									huntingGroundEast = Double.parseDouble(property.getFirstChild().getNodeValue());
								else if (name.equalsIgnoreCase("west"))			                       
									huntingGroundWest = Double.parseDouble(property.getFirstChild().getNodeValue());
							}

							HuntingGrounds.addHuntingGround(huntingGroundName, huntingGroundNorth, huntingGroundSouth, huntingGroundEast, huntingGroundWest);
						}
					}
					catch (Exception e)
					{
						throw new RuntimeException(e);
					}
				}
				catch (IOException e)
				{
					throw new RuntimeException(e);
				}

				// Build the snipes database

				try {

					InputStream inputStream = assetManager.open("snipes.xml");

					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

					try {
						
						DocumentBuilder builder = factory.newDocumentBuilder();
						Document dom = builder.parse(inputStream);

						Element root = dom.getDocumentElement();
						NodeList items = root.getElementsByTagName("snipe");

						for (int i = 0; i < items.getLength(); i++) {
							
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values)  
		{
			progressDialog.setProgress(values[0]);  
		}

		@Override
		protected void onPostExecute(Void result)  
		{
			progressDialog.dismiss();

			setListAdapter(new SimpleAdapter(SnipeHunterMenuActivity.this, getData(), android.R.layout.simple_list_item_1, new String[] { "title" }, new int[] { android.R.id.text1 }));
			getListView().setTextFilterEnabled(true);
		}
	}

	protected List<Map<String,?>> getData()
	{
		List<Map<String,?>> data = new ArrayList<Map<String,?>>();

		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_DEFAULT);

		PackageManager pm = getPackageManager();
		List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

		if (null == list)
			return data;

		int len = list.size();

		for (int i = 0; i < len; i++) {
			ResolveInfo info = list.get(i);

			CharSequence labelSeq = info.loadLabel(pm);

			if ("fct.mpc.snipehunter".equals(info.activityInfo.applicationInfo.packageName))
				addItem(data, labelSeq.toString(), activityIntent(info.activityInfo.applicationInfo.packageName, info.activityInfo.name));
		}

		return data;
	}

	protected void addItem(List<Map<String,?>> data, String name, Intent intent)
	{
		Map<String,Object> temp = new HashMap<String,Object>();
		temp.put("title", name);
		temp.put("intent", intent);
		data.add(temp);
	}

	protected Intent activityIntent(String pkg, String componentName) {
		Intent result = new Intent();
		result.setClassName(pkg, componentName);
		return result;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		Map<?,?> map = (Map<?,?>) l.getItemAtPosition(position);

		Intent intent = (Intent) map.get("intent");
		startActivity(intent);
	}
}
